<template>
  <div class="user-manage">
    <!-- 使用 NavBar 组件 -->
    
    <el-card class="user-list-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
        </div>
      </template>
      
      <!-- 加载状态 -->
      <el-loading v-if="loading" target=".user-list-card" text="加载中..." />

      <!-- 错误提示 -->
      <div v-else-if="error" class="error-message">{{ error }}</div>

      <!-- 用户表格 -->
      <el-table v-else :data="userList" style="width: 100%">
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="warning" @click="resetPassword(scope.row)" :disabled="scope.row.role === '管理员'">重置密码</el-button>
            <el-button size="small" :type="scope.row.status === '正常' ? 'danger' : 'success'"
              @click="toggleBan(scope.row)" :disabled="scope.row.role === '管理员'">
              {{ scope.row.status === '正常' ? '封号' : '解封' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteUser(scope.row)" :disabled="scope.row.role === '管理员'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑用户">
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" />
          <div v-if="usernameExists" class="error-text">用户名已存在</div>
        </el-form-item>
        <el-form-item label="密码" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <el-dialog v-model="secondaryPasswordDialogVisible" title="输入二级密码">
    <el-form :model="secondaryPasswordForm">
      <el-form-item label="二级密码">
        <el-input v-model="secondaryPasswordForm.password" type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="secondaryPasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSecondaryPasswordConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

// 从后端API获取用户数据
const userList = ref([])
const loading = ref(true)
const error = ref(null)
const userStore = useUserStore()
const router = useRouter()

// 提取获取用户列表逻辑为独立函数
const fetchUserList = async () => {
  try {
    loading.value = true
    const response = await axios.get('http://localhost:8080/api/manage')
    console.log('API响应数据:', response.data)
    userList.value = response.data.data || []
    // 过滤掉管理员用户
    userList.value = userList.value.filter(u => u.role !== '管理员')
    // 调试：检查返回的用户数据是否包含password字段
    console.log('用户数据结构:', userList.value[0] ? Object.keys(userList.value[0]) : '无用户数据')
  } catch (err) {
    error.value = '获取用户列表失败: ' + (err.response?.data?.message || err.message)
    console.error('用户数据获取失败:', err)
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  // 详细日志：检查用户状态
  console.log('UserManage页面加载时的用户状态:', { isLoggedIn: userStore.isLoggedIn, role: userStore.role });
  // 检查登录状态和管理员权限
  if (!userStore.isLoggedIn) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  if (userStore.role !== '管理员') {
    ElMessage.error('需要管理员权限访问')
    router.push('/main')
    return
  }
  await fetchUserList()
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEdit = ref(false)
const userForm = ref({ id: null, username: '', password: '' })
// 添加用户名重复检查状态
const usernameExists = ref(false)
// 二级密码相关状态
const secondaryPasswordDialogVisible = ref(false)
const secondaryPasswordForm = ref({ password: '' })
// 模拟二级密码，实际项目中应从安全配置获取
const SECONDARY_PASSWORD = 'hwadee'


// 打开编辑对话框
const openEditDialog = (user) => {
  // 检查权限
  if (!userStore.isLoggedIn || userStore.role !== '管理员') {
    ElMessage.error('无权限执行此操作')
    return
  }
  isEdit.value = true
  const { password, ...userWithoutPassword } = user
  userForm.value = { ...userWithoutPassword }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  // 检查权限
  if (!userStore.isLoggedIn || userStore.role !== '管理员') {
    ElMessage.error('无权限执行此操作')
    return
  }
  usernameExists.value = false
  if (!userForm.value.username.trim()) {
    ElMessage.warning('用户名不能为空')
    return
  }

  // 检查用户名是否已存在（排除当前编辑用户）
  const currentUserId = userForm.value.id
  const duplicateUser = userList.value.some(u => 
    u.id !== currentUserId && u.username === userForm.value.username.trim()
  )

  if (duplicateUser) {
    usernameExists.value = true
    return
  }

  try {
    loading.value = true
    // 修改API路径和请求体格式
    const response = await axios.put('http://localhost:8080/api/manage/update', {
      id: userForm.value.id,
      username: userForm.value.username
    })

    // 检查后端返回的code字段
    if (response.data.code === 200) {
      ElMessage.success('用户编辑成功')
      // 更新本地数据
      const index = userList.value.findIndex(u => u.id === userForm.value.id)
      if (index !== -1) {
        userList.value[index].username = userForm.value.username
      }
      dialogVisible.value = false
    } else {
      ElMessage.error(response.data.msg || '编辑用户失败')
    }
  } catch (err) {
    ElMessage.error('网络错误，无法连接到服务器')
    console.error('编辑用户失败:', err)
  } finally {
    loading.value = false
  }
}

// 重置密码
const resetPassword = async (user) => { 
  // 检查权限
  if (!userStore.isLoggedIn || userStore.role !== '管理员') { 
    ElMessage.error('无权限执行此操作') 
    return 
  }
  try {
    await ElMessageBox.confirm('确定要将该用户密码重置为默认值1234566吗？', '重置密码', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 显示二级密码对话框
    secondaryPasswordDialogVisible.value = true
    // 保存当前要重置密码的用户
    currentUserForReset = user
  } catch (err) {
    if (err === 'cancel') return
    ElMessage.error('操作失败: ' + (err.response?.data?.msg || err.message))
    console.error('重置密码失败:', err)
  }
}

// 定义当前要重置密码的用户
let currentUserForReset = null

// 处理二级密码确认
const handleSecondaryPasswordConfirm = async () => { 
  if (secondaryPasswordForm.value.password === SECONDARY_PASSWORD) {
    secondaryPasswordDialogVisible.value = false
    try {
      loading.value = true
      const response = await axios.post(`http://localhost:8080/api/manage/${currentUserForReset.id}/reset-password`, {
        password: '1234566'  // 设置默认密码
      })

      if (response.data.code === 200) {  // 统一使用code判断
        ElMessage.success('密码重置成功')
        await fetchUserList();
      } else {
        ElMessage.error(response.data.msg || '密码重置失败')
      }
    } catch (err) {
      ElMessage.error('操作失败: ' + (err.response?.data?.msg || err.message))
      console.error('重置密码失败:', err)
    } finally {
      loading.value = false
    }
    secondaryPasswordForm.value.password = ''
  } else {
    ElMessage.error('二级密码错误')
  }
}

// 切换封号状态
const toggleBan = async (user) => {
  // 检查权限
  if (!userStore.isLoggedIn || userStore.role !== '管理员') {
    ElMessage.error('无权限执行此操作')
    return
  }
  // 修改状态值为后端预期的格式（假设后端使用active/inactive）
  const newStatus = user.status === '正常' ? 'inactive' : 'active'
  const actionText = user.status === '正常' ? '封号' : '解封'
  const confirmMessage = `确定要${actionText}该用户吗？`

  try {
    await ElMessageBox.confirm(confirmMessage, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    loading.value = true
    // 修改API路径和请求体格式
    const response = await axios.put(`http://localhost:8080/api/manage/${user.id}/status`, {
      status: newStatus
    })

    if (response.data.code === 200) {  // 统一使用code判断
      ElMessage.success(`${actionText}成功`)
      // 操作成功后刷新用户列表
      await fetchUserList()
    } else {
      ElMessage.error(response.data.msg || `${actionText}失败`)
    }
  } catch (err) {
    if (err === 'cancel') return
    ElMessage.error('操作失败: ' + (err.response?.data?.msg || err.message))
    console.error('切换封号状态失败:', err)
  } finally {
    loading.value = false
  }
}

// 删除用户
const deleteUser = async (user) => {
  // 检查权限
  if (!userStore.isLoggedIn || userStore.role !== '管理员') {
    ElMessage.error('无权限执行此操作')
    return
  }
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？此操作不可恢复！', '危险操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })

    loading.value = true
    const response = await axios.delete(`http://localhost:8080/api/manage/${user.id}`)

    if (response.data.code === 200) {  // 统一使用code判断
      ElMessage.success('用户删除成功')
      userList.value = userList.value.filter(u => u.id !== user.id)
    } else {
      ElMessage.error(response.data.msg || '用户删除失败')
    }
  } catch (err) {
    if (err === 'cancel') return
    ElMessage.error('操作失败: ' + (err.response?.data?.msg || err.message))
    console.error('删除用户失败:', err)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.user-manage {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.user-list-card {
  margin-top: 20px;
}
.password-eye-icon {
  cursor: pointer;
  width: 25px;
  height: 20px;
  margin-left: 5px;
}
.error-message {
  color: #f56c6c;
  background-color: #fef0f0;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 16px;
  text-align: center;
}
.error-text {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
}
</style>
